package offer;

public class SpiralOrder {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 4, 5, 6, 7, 8, 8, 9, 0, 0, 12}};
        int[] ints = new SpiralOrder().spiralOrder(matrix);
        for (int anInt : ints) {
            System.out.println(anInt);
        }
    }


    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return new int[0];
        }
        int[] arr = new int[matrix.length * matrix[0].length];
        int row = matrix.length;
        int column = matrix[0].length;
        recur(0, --row, 0, --column, matrix, arr, 0);
        return arr;
    }

    public void recur(int startRow, int endRow, int startColumn, int endColumn, int[][] matrix, int[] res, int index) {
        for (int i = startColumn; i <= endColumn; i++) {
            if (res.length == index) {
                return;
            }
            res[index++] = matrix[startRow][i];
        }

        for (int i = startRow + 1; i <= endRow; i++) {
            if (res.length == index) {
                return;
            }
            res[index++] = matrix[i][endColumn];
        }

        for (int i = endColumn - 1; i >= startColumn; i--) {
            if (res.length == index) {
                return;
            }
            res[index++] = matrix[endRow][i];
        }

        for (int i = endRow - 1; i >= startRow + 1; i--) {
            if (res.length == index) {
                return;
            }
            res[index++] = matrix[i][startColumn];
        }
        if (startRow >= endRow || startColumn >= endColumn) {
            return;
        }

        recur(++startRow, --endRow, ++startColumn, --endColumn, matrix, res, index);

    }
}
